package com.nl.lib_project.view.textview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.nl.lib_core.tool.extends.dp2px
import com.nl.lib_core.tool.extends.sp2px
import com.nl.lib_project.R

/** 作者:LiBW 创建日期:2022/2/22 描述:更新弹窗 百分比进度条 */
class DownloadProgressView(context: Context, attributeSet: AttributeSet? = null) :
    View(context, attributeSet) {
  private val mPaint = Paint()
  private var radius = 0f
  private var currentProgress = 0
  private var textSize = 0f
  init {
    val array = context.obtainStyledAttributes(attributeSet, R.styleable.DownloadProgressView, 0, 0)
    val r = array.getFloat(R.styleable.DownloadProgressView_view_radius, 5f)
    val s = array.getFloat(R.styleable.DownloadProgressView_view_text_size, 14f)
    radius = context.dp2px(r).toFloat()
    textSize = context.sp2px(s)
    array.recycle()
    mPaint.isAntiAlias = true
    mPaint.textSize = textSize
  }

  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    // 绘制浅蓝色底色的矩形
    mPaint.color = ContextCompat.getColor(context, R.color.color_blue_light)
    canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, mPaint)
    // 绘制深蓝色进度
    mPaint.color = ContextCompat.getColor(context, R.color.project_main_color)
    val mWidth = currentProgress / 100f * width
    canvas.drawRoundRect(0f, 0f, mWidth, height.toFloat(), radius, radius, mPaint)
    // 绘制文字
    val text = "${currentProgress}%"
    mPaint.color = Color.WHITE
    val textWidth = mPaint.measureText(text)
    val textX = (width - textWidth / 2f) / 2f
    val textY = (height + textSize / 2f) / 2f + 4f
    canvas.drawText(text, textX, textY, mPaint)
  }
  /** 当前进度百分比 */
  fun currentProgress(progress: Int) {
    currentProgress = progress
    invalidate()
  }
}
